import cv2
import os

def extract_frames(video_path, output_dir, frame_rate):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 读取视频文件
    video = cv2.VideoCapture(video_path)
    video_fps = int(video.get(cv2.CAP_PROP_FPS))
    
    # 计算间隔帧数
    interval = int(video_fps / frame_rate)
    
    count = 0
    frame_count = 0
    
    while True:
        success, frame = video.read()
        if not success:
            break
        
        # 每隔一定帧数保存一帧
        if count % interval == 0:
            cv2.imwrite(os.path.join(output_dir, f"frame_{frame_count}.jpg"), frame)
            frame_count += 1
        
        count += 1
    
    video.release()
    print(f"Frames extracted: {frame_count}")

# 使用示例
if __name__ == '__main__':
    video_path = r'C:\Users\Umbra\Desktop\coalgange.mp4'  # 视频文件路径
    output_dir = r'C:\Users\Umbra\Desktop\paper\video-fps\origin'         # 输出目录
    frame_rate = 10                # 每秒想要抽取的帧数

    extract_frames(video_path, output_dir, frame_rate)
    print('down!')
